import axios from "axios";
import { useUserStore }  from '@/stores/userStore.js'
import router from '@/router'
import { ElMessage } from "element-plus";

const httpInstance = axios.create({
    baseURL: 'http://localhost:8090',
    timeout: 5000,
})


// 请求拦截器
httpInstance.interceptors.request.use(config => {

    // 从pinia中获取access_token
    const userStore = useUserStore()
    withCredentials: true            // ✅ 允许跨域携带 Cookie（如果后端设置了 allowCredentials）

    const accessToken = userStore.userInfo.accessToken
    if(accessToken) {
        config.headers.Authorization = `Bearer ${accessToken}`
    }

    return config
}, e => Promise.reject(e))

// 响应拦截器
httpInstance.interceptors.response.use(res => res.data, e => {
    // 从pinia中获取access_token
    const userStore = useUserStore()

    // access_token校验
    if(e.response.status === 401) {
        ElMessage.warning('登陆过期，请重新登录')
        userStore.clearAuth()
        router.push('/login')
    }

    return Promise.reject(e)
})

export default httpInstance
